#!/usr/bin/env python

#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

from dbinter import oai_db
from util import *
from operator import itemgetter
import re

# main function
class advanced:
	def __init__(self):
		# connect to the database
		self.db = oai_db()
		try:
			self.db.connect()
			# get total record number
			result = self.db.query( "SELECT count(*) FROM harvestSearch;" )
			self.rec_count = 'Searching ' + commas(result[1][0][0]) + ' records.'
			#self.rec_count = ''

			# get repository list
			self.repList = []
			fields, rows = self.db.query("SELECT repositoryName FROM harvestRepository ORDER BY repositoryName;")
			dKeys = [field[0] for field in fields]

			for row in rows:
				# stitch
				dRow = dict(zip(dKeys,row))

				self.repList.append(dRow['repositoryName'])

			# get active languages list
			self.langList = {}
			fields, rows = self.db.query("SELECT langCode, langDesc FROM harvestLanguageActive ORDER BY langDesc;")
			dKeys = [field[0] for field in fields]

			for row in rows:
				# stitch
				dRow = dict(zip(dKeys,row))

				self.langList[dRow['langCode']] = dRow['langDesc']


			# disconnect from the db
			self.db.disconnect()
		except:
			# db is unavailable
			self.rec_count = 'Database unavailable. Some search features may not work.'

	def process(self):
		# make the page

		# print header
		outbit('pg_header_2')

		outbit('pg_title_1')

		outbit('pg_bar_short')

		outbit('pg_tips')

		print \
"""
<div id="aform1">
	<div id="adiv1">
		<form name="creator" onsubmit="return gen_search();">
		<b>Advanced OAI Search</b><br>
		<br>
		Match all words:<br>
		<input type="text" name="keywords" maxLength=50 size=40><br>
		Match as a phrase:<br>
		<input type="text" name="phrase" maxLength=50 size=40"><br>
		Exclude words:<br>
		<input type="text" name="exclude" maxLength=50 size=40><br>
		Words that must be close to each other:<br>
		<input type="text" name="nearby" maxLength=50 size=40><br>
		Include Results without a detected URL:<br>
		<input type="radio" name="valurl" value="y" checked> Yes
		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		<input type="radio" name="valurl" value="n"> No<br>
		Limit to a Repository:<br>
		<select name="repository">
			<option value="" selected>(All Repositories)</option>
"""

		# combo box for repositories
		for r in self.repList:
			if len(r) > 2:
				# good stopping point for breaking up long names
				shorten = re.compile('(/|\.|-)')
				dr = shorten.split(r)
				ldr = len(dr)
				p = 0
				nr = dr[p]
				while p < ldr:
					try:
						if len(nr+dr[p+1]+dr[p+2]) < 60:
							nr += dr[p+1]
							nr += dr[p+2]
						p += 2
					except:
						break
				option = "	<option value=\"%s\">%s</option>" % (nr,nr)
				print chkenc(option)

		print """
		</select><br>
		Limit to a Language (excludes records with an unspecified language):<br>
		<select name="language">
			<option value="" selected>(Any Language)</option>
"""
		# combo box for languages
		sortVals = sorted(self.langList.items(),key=itemgetter(1),reverse=False)
		for k,v in sortVals:
			if len(k) > 1:
				print "		<option value=\"%s\">%s</option>" % (k,v)

		print """		
		</select>
		<div id="adiv3">
			<b>By fields with priority</b><br><br>
			Title:<br>
			<div>
			<input type="text" name="title" maxLength=50 size=40>
			&nbsp;&nbsp;&nbsp;Low
			<input type="radio" name="titlemod" value="0.3">
			<input type="radio" name="titlemod" value="0.5">
			<input type="radio" name="titlemod" value="0.8">
			<input type="radio" name="titlemod" value="1" checked>
			<input type="radio" name="titlemod" value="1.6">
			<input type="radio" name="titlemod" value="2.3">
			<input type="radio" name="titlemod" value="3">
			High</div>
			Creator/Author:<br>
			<div>
			<input type="text" name="creator" maxLength=50 size=40>
			&nbsp;&nbsp;&nbsp;Low
			<input type="radio" name="creatormod" value="0.3">
			<input type="radio" name="creatormod" value="0.5">
			<input type="radio" name="creatormod" value="0.8">
			<input type="radio" name="creatormod" value="1" checked>
			<input type="radio" name="creatormod" value="1.6">
			<input type="radio" name="creatormod" value="2.3">
			<input type="radio" name="creatormod" value="3">
			High</div>
			Subject:<br>
			<div>
			<input type="text" name="subject" maxLength=50 size=40>
			&nbsp;&nbsp;&nbsp;Low
			<input type="radio" name="subjectmod" value="0.3">
			<input type="radio" name="subjectmod" value="0.5">
			<input type="radio" name="subjectmod" value="0.8">
			<input type="radio" name="subjectmod" value="1" checked>
			<input type="radio" name="subjectmod" value="1.6">
			<input type="radio" name="subjectmod" value="2.3">
			<input type="radio" name="subjectmod" value="3">
			High</div>
		</div>
		<div id="adiv2">
		<br>
		<input type="submit" value="     OAI Search     ">
		</div>
		</form>
	</div>
</div>
"""

		data = (self.rec_count,)
		outbit('pg_footer_2',data)

# begin execution
class advanced_main:
	def __init__(self):
		print "Content-type: text/html\n\n"
		page = advanced()
		data = page.process()

if __name__ == '__main__' or __name__ == 'advanced':
	run = advanced_main()

#eof

